//
//  KKExchangeRateManager.m
//  FreightAssistant
//
//  Created by leo on 15/12/12.
//  Copyright © 2015年 leo. All rights reserved.
//

#import "KKExchangeRateManager.h"

#define APIKey @"0d1ef01d75b78af02dda631d5a49d746"

#define APIURL @"http://apis.baidu.com/apistore/currencyservice/type"

#define API_CURRENCY @"http://apis.baidu.com/apistore/currencyservice/currency"

static NSString *KKExchangeRateFileName = @"currency.cat";

@interface KKExchangeRateManager() {
    
    NSMutableDictionary *_exchangeRateDictionary;
    NSString *_filePath;
    
    NSArray *_currencyTypes;
}

@end

@implementation KKExchangeRateManager


+ (instancetype)defaultManager {
    static KKExchangeRateManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKExchangeRateManager new];
    });
    
    return manager;
}

- (NSArray *)currencyItems {
    
    return [NSArray arrayWithArray: _currencyTypes];
}


- (instancetype)init {
    self = [super init];
    if (self) {
        
        _currencyTypes = @[@"CNY",@"USD",@"HKD",@"EUR",@"GBP",@"JPY",@"AUD",@"KRW",@"CAD"];
        
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        _filePath = [documentsDirectory stringByAppendingPathComponent: KKExchangeRateFileName];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath: _filePath]) {
            NSData *fileData = [NSData dataWithContentsOfFile: _filePath];
            _exchangeRateDictionary = [NSJSONSerialization JSONObjectWithData: fileData options: NSJSONReadingMutableContainers error: nil];
        }
        else {
            _exchangeRateDictionary = [NSMutableDictionary dictionary];
            
            [self updateExchangeValues];
        }
    }
    return self;
}


- (double)exchangeValueFromCurrency:(NSString *)fromCurrency toCurrency:(NSString *)toCurrency amount:(double)amount {

    if (fromCurrency == nil || toCurrency == nil) {
        return 0.0;
    }
    
    if ([fromCurrency isEqualToString: KKExchangeRateTypeCNY]) {
        
        NSNumber *toValue = _exchangeRateDictionary[toCurrency];
        if (toValue) {
            return amount * [toValue doubleValue];
        }
    }
    else {
        NSNumber *fromValue = _exchangeRateDictionary[fromCurrency];
        NSNumber *toValue = _exchangeRateDictionary[toCurrency];
        
        if (fromCurrency && toValue) {
            double tempValue = amount / [fromValue doubleValue];
            return tempValue * [toValue doubleValue];
        }
    }
    
    return 0.0;
}

- (void)updateExchangeValues {
    
    [_exchangeRateDictionary removeAllObjects];
    
    for (NSString *type in _currencyTypes) {
        [self downLoadDataFromWeb: type];
    }
}

#pragma mark - Private methods

- (void)downLoadDataFromWeb:(NSString *)type {
    
    if (type == nil) {
        return;
    }
    
    NSString *parameterString = [NSString stringWithFormat: @"fromCurrency=CNY&toCurrency=%@&amount=1", type];
    NSString *urlStr = [[NSString alloc]initWithFormat: @"%@?%@", API_CURRENCY, parameterString];
    NSURL *url = [NSURL URLWithString: urlStr];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"GET"];
    [request addValue: APIKey forHTTPHeaderField: @"apikey"];
    [NSURLConnection sendAsynchronousRequest: request
                                       queue: [NSOperationQueue mainQueue]
                           completionHandler: ^(NSURLResponse *response, NSData *data, NSError *error){
                               
                               if (data) {
                                   NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error: nil];
                                   
                                   NSDictionary *retData = responseDictionary[@"retData"];
                                   
                                   NSString *currencyValue = retData[@"currency"];
                                   [_exchangeRateDictionary setValue: currencyValue forKey: type];
                                   
                                   
                                   if (_exchangeRateDictionary.count == _currencyTypes.count) {
                                       [self saveDataToCacheFile];
                                   }
                               }
                           }];
}


- (void)saveDataToCacheFile {
    
    NSData *cacheData = [NSJSONSerialization dataWithJSONObject: _exchangeRateDictionary options: NSJSONWritingPrettyPrinted error: nil];
    
    [cacheData writeToFile: _filePath atomically: true];
}

@end
